package com.westos.spring.wenjian;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class ResultSetListImpl implements ResultSetToList {

	@Override
	public List<Object> resultsettolist(ResultSet rs, Class<?> clazz) {
		List<Object> list = new ArrayList<>();
		Field[] fields = clazz.getDeclaredFields();
		try {
			while (rs.next()) {
				Object obj = clazz.newInstance();
				for (int i = 0; i < fields.length; i++) {
					String filedname = fields[i].getName();
					String methodname = "set" + StringUtils.capitalize(filedname);
					Method method = clazz.getDeclaredMethod(methodname, fields[i].getType());
					if (StringUtils.equals(fields[i].getType().getName(), "java.lang.String")) {
						method.invoke(obj, rs.getString(fields[i].getName()));
					} else if (StringUtils.equals(fields[i].getType().getName(), "java.lang.Integer")) {
						method.invoke(obj, rs.getInt(fields[i].getName()));
					}
					list.add(obj);
				} 

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	public ResultSet getresultset(ComboPooledDataSource ds) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn = null;
		String sql = "select * from student";
		try {

			conn= ds.getConnection();
			ps =  conn.prepareStatement(sql);
			rs = ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rs;

	}

}
